import services from '../../services/api';
import storage from '../../utils/storage';
const initialState = {
  depts: [],
  dept_name: '',
  dept_id: '',
  orgList: [],
};

// 搜索遍历
const ergodic = (data, value) => {
  let node = '';
  for (let i = 0; i < data.length; i++) {
    if (data[i].dept_id === value) {
      node = data[i];
      break;
    } else {
      if (data[i].child) {
        let res = ergodic(data[i].child, value);
        if (res) {
          node = res;
          break;
        }
      }
    }
  }
  return node;
};
export default {
  name: 'global',
  state: initialState,
  reducers: {
    updateOrg: (state, { data }) => {
      return {
        ...state,
        ...data,
      };
    },
    updateDept: (state, { data }) => {
      return {
        ...state,
        ...data,
      };
    },
    updateDeptName: (state, { data }) => {
      return {
        ...state,
        ...data,
      };
    },
    updateDeptId: (state, { data }) => {
      return {
        ...state,
        ...data,
      };
    },
  },
  effects: {
    queryDept: async ({ params }, { dispatch }) => {
      return services.dept.tree({}).then((res) => {
        if (res.code === 0) {
          // const current = res.data.find(item => item.dept_id === storage.dept);
          const current = ergodic(res.data, storage.dept);
          const dept_name = current ? current.dept_name : '';
          const dept_id = current ? current.dept_id : '';

          dispatch({ type: 'global/updateDept', data: { depts: res.data } });
          dispatch({
            type: 'global/updateDeptName',
            data: {
              dept_name,
            },
          });
          dispatch({
            type: 'global/updateDeptName',
            data: {
              dept_id,
            },
          });
          return res.data;
        }
      });
    },
    // 机构
    queryOrg: async ({ params }, { dispatch }) => {
      return services.portal.orgList().then((res) => {
        if (res.code === '0') {
          const { organizationlist, currentOrganizationCode: code, currentOrganizationName: name } = res.data;
          storage.org = {
            code,
            name,
          };
          dispatch({ type: 'global/updateOrg', data: { orgList: [organizationlist] } });
        }
      });
    },
  },
};
